﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Data.SqlClient;

using Common;



namespace CNCSoft.ErpApps.TMS.Marketing
{
    public partial class MarketingHangNgay : Form
    {
        public MarketingHangNgay()
        {
            InitializeComponent();
        }

        private SqlDataAdapter dataAdapter = new SqlDataAdapter();


        private void MarketingHangNgay_Load(object sender, EventArgs e)
        {
            dataGridView.DataError += new DataGridViewDataErrorEventHandler(dataGridView_DataError);

            txtTuNgay.Text = DateTime.Now.Date.AddDays(-DateTime.Now.Date.Day + 1).ToString("dd/MM/yyyy");
            txtDenNgay.Text = GlobalVariable.WSInfo.WorkingDate.AddDays(15).ToString("dd/MM/yyyy");

            dataGridView.DataSource = bindingSource;
            GetData();
            buildDgridTS();

        }


        private DataTable Populate(string sqlCommand)
        {
            SqlConnection conn = new SqlConnection(GlobalVariable.WSInfo.ConnectionString);
            conn.Open();

            SqlCommand command = new SqlCommand(sqlCommand, conn);
            SqlDataAdapter adapter = new SqlDataAdapter();
            adapter.SelectCommand = command;

            DataTable table = new DataTable();
            table.Locale = System.Globalization.CultureInfo.InvariantCulture;
            adapter.Fill(table);
            conn.Close();
            conn.Dispose();
            
            return table;
        }


        DataTable table = new DataTable();

        private void GetData()
        {
            try
            {
                string strTuNgay = txtTuNgay.getDateValue().Month.ToString("00") + "-" + txtTuNgay.getDateValue().Day.ToString("00") + "-" + txtTuNgay.getDateValue().Year.ToString("0000");
                string strDenNgay = txtDenNgay.getDateValue().Month.ToString("00") + "-" + txtDenNgay.getDateValue().Day.ToString("00") + "-" + txtDenNgay.getDateValue().Year.ToString("0000");
                string strSELECT = "";

                if (GlobalVariable.WSInfo.getAppProperty("Sys.ManagerIDGroup").ToLower().IndexOf(GlobalVariable.WSInfo.UserID.ToLower()) >= 0)
                    //Nguoi manager xem duoc tat car cong viec cua tat ca user
                    strSELECT = "SELECT [ID],[Ngay],[CongViec],[NguoiChiuTrachNhiem],[NguoiReview],[NoiDungReview],[TinhTrang] " +
                                       "FROM Marketing where ngay between '" + strTuNgay + "' AND '" + strDenNgay + "' ";
                else
                    //User binh thuong chi coi duoc cong viec cua minh
                    strSELECT = "SELECT [ID],[Ngay],[CongViec],[NguoiChiuTrachNhiem],[NguoiReview],[NoiDungReview],[TinhTrang] " +
                                       "FROM Marketing where ngay between '" + strTuNgay + "' AND '" + strDenNgay + "' " +
                                       "AND [NguoiChiuTrachNhiem] = '" + GlobalVariable.WSInfo.UserID + "'";

                // Create a new data adapter based on the specified query.
                dataAdapter = new SqlDataAdapter(strSELECT, GlobalVariable.WSInfo.ConnectionString);

                // Create a command builder to generate SQL update, insert, and
                // delete commands based on selectCommand. These are used to
                // update the database.
                SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

                // Populate a new data table and bind it to the BindingSource.
                table.Locale = System.Globalization.CultureInfo.InvariantCulture;
                table.Clear();
                dataAdapter.Fill(table);
                table.Columns["TinhTrang"].DefaultValue = "Chưa start";
                table.Columns["NguoiChiuTrachNhiem"].DefaultValue = GlobalVariable.WSInfo.UserID;
                bindingSource.DataSource = table;

            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void buildDgridTS()
        {
            try
            {
                //Remove cot ID
                dataGridView.Columns.Remove("ID");

                //Ngay
                dataGridView.Columns[0].HeaderText = "Ngày";
                dataGridView.Columns[0].Width = 80;

                //Cot mon hoc de sau cung tinh toan kich thuoc con lai cua luoi

                //Cong viec
                dataGridView.Columns[1].HeaderText = "Công việc";
                dataGridView.Columns[1].Width = 300;
                dataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCells;
                dataGridView.DefaultCellStyle.WrapMode = DataGridViewTriState.True;

                //Trách nhiệm của
                DataGridViewComboBoxColumn comboboxColumnThucHien = new DataGridViewComboBoxColumn();
                comboboxColumnThucHien.DataPropertyName = "NguoiChiuTrachNhiem";
                comboboxColumnThucHien.HeaderText = "Trách nhiệm của";
                comboboxColumnThucHien.DropDownWidth = 300;
                comboboxColumnThucHien.Width = 120;
                comboboxColumnThucHien.FlatStyle = FlatStyle.Flat;
                comboboxColumnThucHien.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
                comboboxColumnThucHien.DataSource = Populate("SELECT UserID, FullName FROM SYS_List_User WHERE IsLocked = 0 ");
                comboboxColumnThucHien.ValueMember = "UserID";
                comboboxColumnThucHien.DisplayMember = "UserID";

                dataGridView.Columns.Remove("NguoiChiuTrachNhiem");
                dataGridView.Columns.Insert(2, comboboxColumnThucHien);


                //Nguoi review
                DataGridViewComboBoxColumn comboboxColumnReview = new DataGridViewComboBoxColumn();
                comboboxColumnReview.DataPropertyName = "NguoiReview";
                comboboxColumnReview.HeaderText = "Review bởi";
                comboboxColumnReview.DropDownWidth = 300;
                comboboxColumnReview.Width = 120;
                comboboxColumnReview.FlatStyle = FlatStyle.Flat;
                comboboxColumnReview.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
                comboboxColumnReview.DataSource = Populate("SELECT UserID, FullName FROM SYS_List_User WHERE IsLocked = 0 ");
                comboboxColumnReview.ValueMember = "UserID";
                comboboxColumnReview.DisplayMember = "UserID";
                dataGridView.Columns.Remove("NguoiReview");
                dataGridView.Columns.Insert(3, comboboxColumnReview);

                //Tinh trang
                DataGridViewComboBoxColumn comboboxColumn = new DataGridViewComboBoxColumn();
                comboboxColumn.DataPropertyName = "TinhTrang";
                comboboxColumn.HeaderText = "Tình trạng";
                comboboxColumn.DropDownWidth = 160;
                comboboxColumn.Width = 110;
                comboboxColumn.FlatStyle = FlatStyle.Flat;
                comboboxColumn.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                comboboxColumn.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
                comboboxColumn.Items.AddRange("Chưa start", "Đang TH", "Hoàn thành", "Không TH");
                dataGridView.Columns.Remove("TinhTrang");
                dataGridView.Columns.Insert(5, comboboxColumn);

                int intChieuRongDadung = 0;
                for (int i = 0; i < dataGridView.Columns.Count; i++)
                    if (i != 4) intChieuRongDadung += dataGridView.Columns[i].Width;

                //Nội dung review
                dataGridView.Columns[4].HeaderText = "Nội dung review";
                dataGridView.Columns[4].Width = dataGridView.Width - intChieuRongDadung - 60;

                // Set the background color for all rows and for alternating rows. 
                // The value for alternating rows overrides the value for all rows. 
                dataGridView.RowHeadersDefaultCellStyle.BackColor = Color.FromArgb(255, 223, 83);
                dataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(255, 223, 83);
                dataGridView.ColumnHeadersDefaultCellStyle.ForeColor = Color.FromArgb(204, 0, 0);

                dataGridView.RowsDefaultCellStyle.BackColor = Color.White;
                dataGridView.AlternatingRowsDefaultCellStyle.BackColor = Color.WhiteSmoke;

                dataGridView.RowHeadersWidth = 25;
                dataGridView.GridColor = Color.FromArgb(255, 243, 219);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "buildDgridTS");
            }

        }

        private void MarketingHangNgay_Resize(object sender, EventArgs e)
        {
            int intChieuRongDadung = 0;
            for (int i = 0; i < dataGridView.Columns.Count; i++)
                if (i != 4) intChieuRongDadung += dataGridView.Columns[i].Width;
            //Mon hoc
            try
            {
                dataGridView.Columns[4].Width = dataGridView.Width - intChieuRongDadung - 60;
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }

        private void cmdCapNhat_Click(object sender, EventArgs e)
        {
            // Update the database with the user's changes.
            dataAdapter.Update((DataTable)bindingSource.DataSource);
        }

        private void cmdLoc_Click(object sender, EventArgs e)
        {
            GetData();
        }

        /*
        private void cmdRefresh_Click(object sender, EventArgs e)
        {
            // Reload the data from the database.
            GetData(dataAdapter.SelectCommand.CommandText);
        }
        */

        private void dataGridView_DataError(object sender, DataGridViewDataErrorEventArgs anError)
        {

            //MessageBox.Show("Lỗi số liệu " + anError.Context.ToString());
            //MessageBox.Show("Lỗi số liệu \nNhập lại hoặc bấm ESC", "Data error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            if (anError.Context == DataGridViewDataErrorContexts.Commit)
            {
                MessageBox.Show("Commit error");
            }
            if (anError.Context == DataGridViewDataErrorContexts.CurrentCellChange)
            {
                MessageBox.Show("Cell change");
            }
            if (anError.Context == DataGridViewDataErrorContexts.Parsing)
            {
                MessageBox.Show("parsing error");
            }
            if (anError.Context == DataGridViewDataErrorContexts.LeaveControl)
            {
                MessageBox.Show("leave control error");
            }

            if ((anError.Exception) is ConstraintException)
            {
                DataGridView view = (DataGridView)sender;
                view.Rows[anError.RowIndex].ErrorText = "Lỗi số liệu";
                view.Rows[anError.RowIndex].Cells[anError.ColumnIndex].ErrorText = "Lỗi số liệu";

                anError.ThrowException = false;
            }
        }

        private bool bReturnHomnay = false;

        private void cmdHomQua_Click(object sender, EventArgs e)
        {
            if (!bReturnHomnay)
            {
                cmdHomNay_Click(sender, e);
                bReturnHomnay = true;
            }
            
            txtTuNgay.Text = txtTuNgay.getDateValue().AddDays(-1).ToString("dd/MM/yyyy");   //DateTime.Now.Date.AddDays(-1).ToString("dd/MM/yyyy");
            txtDenNgay.Text = txtTuNgay.Text;

            cmdLoc_Click(sender, e);
        }

        private void cmdHomNay_Click(object sender, EventArgs e)
        {
            txtTuNgay.Text = DateTime.Now.Date.ToString("dd/MM/yyyy");
            txtDenNgay.Text = txtTuNgay.Text;

            cmdLoc_Click(sender, e);
        }

        private void cmdNgayMai_Click(object sender, EventArgs e)
        {
            if (!bReturnHomnay)
            {
                cmdHomNay_Click(sender, e);
                bReturnHomnay = true;
            }

            txtTuNgay.Text = txtTuNgay.getDateValue().AddDays(+1).ToString("dd/MM/yyyy");   //DateTime.Now.Date.AddDays(-1).ToString("dd/MM/yyyy");
            txtDenNgay.Text = txtTuNgay.Text;

            cmdLoc_Click(sender, e);
        }



    }
}
